package com.chapter.sample.redis.service;

import com.chapter.sample.entity.member.MemberEntity;
import com.chapter.sample.redis.utils.CheckUtils;
import com.chapter.sample.service.MemberService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
@Slf4j
public class CustomerService {
    public static final String CACHE_KEY_CUSTOMER = "customer:";

    @Autowired
    private MemberService memberService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private CheckUtils checkUtils;

    //写操作
    public void addCustomer(MemberEntity member) {
        boolean save = memberService.save(member);
        System.out.println(member.getId());
        if (save) {
            //Mysql插入成功，需要重新查询一次将数据捞出来，写入redis
            MemberEntity byId = memberService.getById(member.getId());
            //redis缓存key
            String key = CACHE_KEY_CUSTOMER + member.getId();

            //捞出来的数据写入redis
            redisTemplate.opsForValue().set(key, member);
        }
    }

    public MemberEntity findMemberById(Integer memberId) {
        MemberEntity member = null;
        //缓存redis的key的名称
        String key = CACHE_KEY_CUSTOMER + memberId;

        //1、先去redis查询
        member = (MemberEntity) redisTemplate.opsForValue().get(key);
        //2 redis有 直接返回，没有再进去查询mysql
        if (Objects.isNull(member)) {
            //3、再去查询mysql
            member = memberService.getById(memberId);
            //3.1、mysql有，redis无
            if (Objects.nonNull(member)) {
                //3.2把mysql查出来的数据写回redis,保持一致性
                redisTemplate.opsForValue().set(key, member);
            }
        }
        return member;
    }

    public MemberEntity findMemberByIdWithBloomFilter(Integer memberId) {
        MemberEntity member = null;
        //缓存redis的key的名称
        String key = CACHE_KEY_CUSTOMER + memberId;

        //布隆过滤器check，无绝对无，有是可能有
        //=================================================
        if (!checkUtils.checkWithBloomFilter("whitelistCustomer", key)) {
            log.info("白名单无此顾客，不可用访问！「{}」", key);
            return null;
        }
        //=================================================

        //1、先去redis查询
        member = (MemberEntity) redisTemplate.opsForValue().get(key);
        //2 redis有 直接返回，没有再进去查询mysql
        if (Objects.isNull(member)) {
            //3、再去查询mysql
            member = memberService.getById(memberId);
            //3.1、mysql有，redis无
            if (Objects.nonNull(member)) {
                //3.2把mysql查出来的数据写回redis,保持一致性
                redisTemplate.opsForValue().set(key, member);
            }
        }
        return member;
    }
}
